﻿# --------------------------- #
# Network Share Configuration #
# --------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing network share configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL
$access = ""
$acls = ""
foreach ($permission in $script.permissions.permission)
{
	$access += "`"/grant:$($permission.account),$($permission.access)`" "
	$acls += "`"$($permission.account):$($permission.acl)`" "
}
Invoke-Command -Session $session -ScriptBlock {
	param([string]$name, [string]$folder, [string]$access, [string]$acls)
	# Create folder
	if (!(Test-Path $folder))
	{
		New-Item $folder -ItemType Directory | Out-Null
	}
    if (!(Test-Path \\$Env:COMPUTERNAME\$name))
    {
	    # Share folder
	    net share "$name=$folder" $access | Out-Null
	    # Set folder security
	    Icacls "$folder" /grant:r $acls | Out-Null
    }
} -ArgumentList $script.name, $script.folder, $access, $acls
Remove-PSSession $session
Write-Text "done."